$(function() {
    /**
	 * 商品的列表数据获取并展示在页面中
	 */
    var page = 1;
    var pageSize = 10;
    var totalPage = 0;

    getData();

    function getData() {
        $.ajax({
            type: "GET",
            url: ajaxUrl("queryProductDetailList"),
            data: {
                page: page,
                size: pageSize,
            },
            success: function(result) {
                // console.log(result);

                totalPage = Math.ceil(result.data.total / pageSize);
                var html = template("productTpl", result.data);
                $("#productBox").html(html);
            }
        });
    }

    $("#nextBtn").on("click", function() {
        page ++;
        if (page > totalPage) {
            page = totalPage;
            alert("已经最后一页了");
            return;
        }
        getData();
    });
    $("#prevBtn").on("click", function() {
        page --;
        if (page < 1) {
            page = 1;
            alert("已经第一页了");
            return;
        }
        getData();
    });

    /**
	 * 添加商品
	 * 1.获取二级分类并展示在选择框中
	 * 2.实现图片上传
	 * 3.实现添加商品
	 */
    $.ajax({
		type: 'GET',
		url: ajaxUrl("querySecondCategoryPaging"),
		data: {
			page: 1,
			pageSize: 100
		},
		success: function(res){
			console.log(res);

			var html = template("secondTpl", res.data);
			$('#secondBox').html(html);
		}
    });
    
    /**
     * 图片上传
     */
    var imageArray = [];
    $('#fileUpload').fileupload({
	    dataType: 'json',
	    done: function (e, data) {
            // console.log(data);
	    	imageArray.push(data.result);
	    }
    });
    
    $('#addProduct').on('click', function(){

		var proName = $.trim($("[name='proName']").val());
		var oldPrice = $.trim($("[name='oldPrice']").val());
		var price = $.trim($("[name='price']").val());
		var proDesc = $.trim($("[name='proDesc']").val());
		var size = $.trim($("[name='size']").val());
		var num = $.trim($("[name='num']").val());
		var brandId = $.trim($("[name='brandId']").val());

		$.ajax({
			type: 'POST',
			url: ajaxUrl("addProduct"),
			data: {
				proName: proName,
				oldPrice: oldPrice,
				price: price,
				proDesc: proDesc,
				size: size,
				num: num,
				brandId: brandId,
				statu: 1,
				pic: imageArray
			},
			success: function(res){
				if(res.code === 200){
					location.reload();
				} else {
					alert(res.message);
				}
			}
		});
	});
});